<template>
  <div class="my-box">
    <el-form ref="configLscFormRef" :model="form" :rules="rules" label-width="120px" class="my-form">
      <el-form-item label-width="0">
        <span style="font-size: 25px;font-weight: bold;margin-left: 20px">模型配置</span>
      </el-form-item>
      <el-form-item label="所选模型：">
        <el-input v-model="modelSelect" :placeholder="modelSelect" :disabled="true" class="item" />
      </el-form-item>
      <el-form-item label="时间步长：" prop="timeSteps">
        <el-input v-model="form.timeSteps" placeholder="请输入时间步长" style="width: 750px" />
        <el-select placeholder="基于数据集选择" style="margin-left: 10px"></el-select>
      </el-form-item>
      <el-form-item label="特征维度：" prop="sensorDim">
        <el-input v-model="form.sensorDim" placeholder="请输入特征维度" class="item" />
      </el-form-item>
      <el-form-item label="模型维度：" prop="modelDim">
        <el-input v-model="form.modelDim" placeholder="请输入模型维度" class="item" />
      </el-form-item>
      <el-form-item label="隐藏层节点：" prop="numHiddens">
        <el-input v-model="form.numHiddens" placeholder="请输入隐藏层节点数" class="item" />
      </el-form-item>
      <el-form-item label="隐藏层层数：" prop="numLayers">
        <el-input v-model="form.numLayers" placeholder="请输入隐藏层层数" class="item" />
      </el-form-item>
      <el-form-item label="激活函数：" prop="activiateType">
        <el-radio-group v-model="form.activiateType">
          <el-radio v-for="dict in lsc_activate_type" :key="dict.value" :label="dict.value" :value="dict.value" border>
            {{dict.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="线性层初始化：" prop="linerInitType">
        <el-radio-group v-model="form.linerInitType">
          <el-radio v-for="dict in lsc_linear_init" :key="dict.value" :label="dict.value" :value="dict.value" border>
            {{dict.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="模型归一化：" prop="modelNormalType">
        <el-radio-group v-model="form.modelNormalType">
          <el-radio v-for="dict in lsc_model_normal" :key="dict.value" :label="dict.value" :value="dict.value" border>
            {{dict.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div class="my-form" style="margin-top: 10px">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">保存配置</el-button>
      <el-button @click="reset">重置参数</el-button>
    </div>
  </div>
</template>

<script setup name="ConfigLsc" lang="ts">
import { listConfigLsc, getConfigLsc, delConfigLsc, addConfigLsc, updateConfigLsc } from '@/api/lsc/modelConfig';
import { ConfigLscVO, ConfigLscQuery, ConfigLscForm } from '@/api/lsc/modelConfig/types';
import { getLsc, updateStatus } from "@/api/lsc/dataset";
import { getLscModel, updateModelStatus } from "@/api/lsc/model";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const configLscList = ref<ConfigLscVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const modelSelect = ref("")
const dataId = ref("")

const queryFormRef = ref<ElFormInstance>();
const configLscFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ConfigLscForm = {
  id: undefined,
  modelId: undefined,
  timeSteps: undefined,
  sensorDim: undefined,
  modelDim: undefined,
  numHiddens: undefined,
  numLayers: undefined,
  linerInitType: undefined,
  activiateType: undefined,
  modelNormalType: undefined
}
const data = reactive<PageData<ConfigLscForm, ConfigLscQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelId: undefined,
    timeSteps: undefined,
    sensorDim: undefined,
    modelDim: undefined,
    numHiddens: undefined,
    numLayers: undefined,
    linerInitType: undefined,
    activiateType: undefined,
    modelNormalType: undefined,
    params: {
    }
  },
  rules: {
    modelId: [
      { required: true, message: "模型id不能为空", trigger: "blur" }
    ],
    timeSteps: [
      { required: true, message: "时间步长不能为空", trigger: "blur" }
    ],
    sensorDim: [
      { required: true, message: "特征维度不能为空", trigger: "blur" }
    ],
    modelDim: [
      { required: true, message: "模型维度不能为空", trigger: "blur" }
    ],
    numHiddens: [
      { required: true, message: "隐藏层节点不能为空", trigger: "blur" }
    ],
    numLayers: [
      { required: true, message: "隐藏层层数不能为空", trigger: "blur" }
    ],
    linerInitType: [
      { required: true, message: "初始化线性层不能为空", trigger: "change" }
    ],
    activiateType: [
      { required: true, message: "激活函数不能为空", trigger: "change" }
    ],
    modelNormalType: [
      { required: true, message: "模型归一化类型不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const {lsc_model_type, lsc_features_type, lsc_activate_type, lsc_linear_init, lsc_model_normal} = toRefs<any>(
  proxy?.useDict('lsc_model_type', 'lsc_features_type', 'lsc_activate_type', 'lsc_linear_init', 'lsc_model_normal')
)

onMounted(() => {
  init();
})

const init = () => {
  getDataInfo();
}
const getFeatures = (features: string) => {
  const list = features.split(',');
  const res = ref<Array<string | number>>([])
  list.forEach(l => {
    res.value.push(lsc_features_type.value.find((item: { value: any; }) => item.value === l)?.label);
  })
  return res.value.join(', ');
}

const getDataInfo = async () => {
  dataId.value = String(localStorage.getItem("modelId"));
  form.value.modelId = dataId.value
  const res = await getLscModel(dataId.value);
  if (res.code === 200) {
    const modelType = lsc_model_type.value.find((item: any) => {
      return item.value == res.data.modelType;
    }).label;
    modelSelect.value = res.data.modelName + "（类型：" + modelType + ", ";
    modelSelect.value = modelSelect.value + "特征：" + getFeatures(String(res.data.modelFeatures)) + "）"
  }
}

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listConfigLsc(queryParams.value);
  configLscList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  configLscFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ConfigLscVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加【请填写功能名称】";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ConfigLscVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getConfigLsc(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改【请填写功能名称】";
}

/** 提交按钮 */
const submitForm = () => {
  configLscFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateConfigLsc(form.value).then(() => {
          updateModelStatus(Object.assign({
            id: dataId.value,
            modelStatus: 1,
          }))
        }).catch(e => {
          updateModelStatus(Object.assign({
            id: dataId.value,
            modelStatus: 2,
          }))
        });
      } else {
        await addConfigLsc(form.value).then(() => {
          updateModelStatus(Object.assign({
            id: dataId.value,
            modelStatus: 1,
          }))
        }).catch(e => {
          updateModelStatus(Object.assign({
            id: dataId.value,
            modelStatus: 2,
          }))
        });
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ConfigLscVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除【请填写功能名称】编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delConfigLsc(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/configLsc/export', {
    ...queryParams.value
  }, `configLsc_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style>
/* 样式 */
.my-box {
  width: 100%;
  height: 100%;
  background-color: #1ab394;
  padding: 10px
}
.my-form {
  width: 100%;
  height: 100%;
  background-color: #FFFFFF;
  padding: 20px;
  border-radius: 10px;
}
.item{
  max-width: 1000px;
}
</style>
